package com.henry.chatkit.weight.badgeview

import android.annotation.SuppressLint
import android.content.Context
import android.graphics.Canvas
import android.graphics.Color
import android.graphics.Paint
import android.graphics.RectF
import android.util.AttributeSet
import android.util.TypedValue
import android.view.Gravity
import androidx.appcompat.widget.AppCompatTextView
import com.henry.chatkit.utils.SizeUtils


class BadgeView @JvmOverloads constructor(context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0)
    : AppCompatTextView(context, attrs, defStyleAttr) {

    private val mNormalSize: Int = SizeUtils.dp2px(18)
    private val mPaint: Paint by lazy { Paint() }

    init {
        mPaint.color = Color.RED
        setTextColor(Color.WHITE)
        setTextSize(TypedValue.COMPLEX_UNIT_SP, 12f)
        gravity = Gravity.CENTER
    }

    fun setNumber(number: Int) {
        visibility = if (number == 0) {
            GONE
        } else {
            VISIBLE
        }
        var string = number.toString()
        if (number < 0) {
            string = ""
        } else if (number > 99) {
            string = "99+"
        }
        text = string
    }

    @SuppressLint("DrawAllocation")
    override fun onDraw(canvas: Canvas) {
        if (text.isEmpty()) {
            // 没有字符，就在本View中心画一个小圆点
            val l: Int = (measuredWidth - SizeUtils.dp2px(10)) / 2
            val r = measuredWidth - l
            canvas.drawOval(RectF(l.toFloat(), l.toFloat(), r.toFloat(), r.toFloat()), mPaint)
        } else if (text.length == 1) {
            canvas.drawOval(RectF(0F, 0F, mNormalSize.toFloat(), mNormalSize.toFloat()), mPaint)
        } else if (text.length > 1) {
            canvas.drawRoundRect(
                RectF(0F, 0F, measuredWidth.toFloat(), measuredHeight.toFloat()),
                (measuredHeight / 2).toFloat(), (measuredHeight / 2).toFloat(), mPaint
            )
        }
        super.onDraw(canvas)
    }

    override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
        var width = mNormalSize
        val height = mNormalSize
        if (text.length > 1) {
            width = mNormalSize + SizeUtils.dp2px((text.length - 1) * 5)
        }
        setMeasuredDimension(width, height)
    }

}